<?php

class Ext_Publish_Attachment_Delete_Adapter_Image implements Ext_Publish_Attachment_Delete_Interface
{
    protected $_articleId;
    protected $_attachmentImageId;
    
    protected $_messager;
    const RECORD_NOT_FOUND  = 'recordNotFound';
    protected $_messageTemplates = array(
        self::RECORD_NOT_FOUND  => "Record not found.",
    );
    
    public function __construct($articleId, $attachmentImageId)
    {
        $this->_articleId         = $articleId;
        $this->_attachmentImageId = $attachmentImageId;
        $this->_messager          = new Ext_Messager($this->_messageTemplates);
    }
    
    public function delete()
    {
        $_result = array(
            'code'      => Ext_Publish_Attachment_Delete_Result::FAILURE,
            'datas'     => array(),
            'messages'  => array(),
        );
        
        $article = App_Model_DbTable_Article::getInstance()->getRowById($this->_articleId);
        if(!$article){
            throw new Ext_Publish_Attachment_Delete_Exception("Article record not found.");
        }
        $attachments = $article['attachments'];
        
        $attachmentsArray = unserialize($attachments);
        if(!is_array($attachmentsArray)){
            $_result['messages'][] = $this->_messager->addMessage(self::RECORD_NOT_FOUND);
            return new Ext_Publish_Attachment_Delete_Result($_result['code'], $_result['messages']);
        }
        $newAttachmentsArray = array();
        for($i=0;$i<count($attachmentsArray);$i++){
            $attachment = $attachmentsArray[$i];
            if($attachment['type'] == 'image' && $attachment['id'] == $this->_attachmentImageId){
                continue;
            }
            
            $newAttachmentsArray[] = $attachment;
        }
        if($attachmentsArray){
            $row = array(
                    'attachments' => serialize($newAttachmentsArray),
            );
            App_Model_DbTable_Article::getInstance()->addOld($row, $this->_articleId);
        }
        
        $imager = new Ext_Article_Attachment_Image($this->_articleId);
        $imager->del($this->_attachmentImageId);
        
        $_result['code'] = Ext_Publish_Attachment_Delete_Result::SUCCESS;
        return new Ext_Publish_Attachment_Delete_Result($_result['code'], $_result['messages']);
    }
}
